#!/usr/bin/env python
import sys
import time
import uuid

import pika

ins_id = "111111111"
exchange_single = ins_id + "-single"
exchange_all = ins_id + "-all"


connection = pika.BlockingConnection(pika.ConnectionParameters(
    host='ek.hongen.com',
    credentials=pika.credentials.PlainCredentials(username="hongen", password="hongen"),
))
channel = connection.channel()

channel.exchange_declare(exchange=exchange_all,
                         exchange_type='topic')
channel.exchange_declare(exchange=exchange_single,
                         exchange_type='direct')
device_id = sys.argv[1] if len(sys.argv) > 1 and sys.argv[1] != '_' else '99'
queue_name = ins_id + "-" + device_id
channel.queue_declare(queue=queue_name, exclusive=True)

channel.queue_declare(queue=ins_id, exclusive=False)

channel.queue_bind(exchange=exchange_single,
                   queue=ins_id,
                   routing_key='')

for binding_key in ["*.stop", "*.exec", "*."+device_id]:
    channel.queue_bind(exchange=exchange_all,
                       queue=queue_name,
                       routing_key=binding_key)

print(' [*] Waiting for logs. To exit press CTRL+C')


def callback(ch, method, properties, body):
    print(" [x] %s" % body.decode() + " " + method.routing_key)


channel.basic_consume(queue_name, callback, auto_ack=True)
channel.basic_consume(ins_id, callback, auto_ack=True)

channel.start_consuming()
